<template>
	<view style="visibility:hide" :params="{ token, tenantId, api }" :change:params="uploadModule.params"></view>
</template>

<script>
	import cache from '@/utils/cache';
	export default {
		data() {
			return {
				token: '',
				tenantId: '',
				api: '/oss/sysOss/upload',
			};
		},
		methods: {
            sendMsg(msg){
				this.$emit('receive', msg);
			}
		},
		mounted() {
			this.token = cache.get('token');
			this.tenantId = cache.get('tenantId');
		},
	};
</script>
<script module="uploadModule" lang="renderjs">
	import {
		NativeEventSource,
		EventSourcePolyfill
	} from 'event-source-polyfill';
	let sseEventSource = NativeEventSource || EventSourcePolyfill;
	if (sseEventSource !== null) sseEventSource.close && sseEventSource.close();
	export default {
		data() {
			return {
				token: '',
				tenantId: '',
				api: ''
			}
		},
		methods: {
			params(newValue) {
				const {
					token,
					tenantId,
					api
				} = newValue;
				this.token = token;
				this.tenantId = tenantId;
				this.api = api
			},
			sseOpen(){
				const sseEventSource = new EventSourcePolyfill(`http://192.168.19.107:9088/sse/info`, {
					headers: {
						Authorization: this.token ? 'Bearer ' + this.token : '',
						'TENANT-ID': this.tenantId,
						VERSION: 'zxl',
					},
					heartbeatTimeout: 60 * 1000,
				});
				sseEventSource.onopen = (event) => {
					console.log(event, 'SSE已开启');
				};
				
				sseEventSource.onerror = (event) => {
					console.log('sse连接错误', event);
				};
				
				sseEventSource.onmessage = (event) => {
					const msg = JSON.parse(event.data);
					this.$ownerInstance.callMethod('sendMsg', msg)
				}
			}
		},
		mounted() {
			this.$nextTick(() => {
				setTimeout(() => {
				   this.sseOpen();
				})
			}, 50)
		}
	}
</script>
<style>

</style>